package com.onesports.intelligent.k12.polarlight.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.onesports.intelligent.k12.polarlight.common.utils.Result;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author aj
 * 后台登录失败处理
 */
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException {
        Result result = new Result();
        String msg = "您输入的帐号或密码不正确，请重新输入！";
        if (e instanceof DisabledException) {
            msg = "您输入的账号已经停用，请联系管理员处理！";
        } else if (e instanceof UsernameNotFoundException) {
            msg = "您输入的账号不存在或已禁用，请联系管理员处理！";
        } else if (e instanceof InternalAuthenticationServiceException) {
            msg = e.getMessage();
        }
        result.setCode(Result.UNAUTHORIZED);
        result.setMsg(msg);
        ObjectMapper mapper = new ObjectMapper();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().append(mapper.writeValueAsString(result));
    }

}
